import pagesJson from '@/pages.json'
import {queryParams} from '@/script/tools.js'
const {pages, subPackages} = pagesJson
let routerArr = [...pages]
subPackages.forEach(root => {
	root.pages.map(i => i.root = root.root)
	routerArr = [...routerArr, ...root.pages]
})
export const router = {
	push: ({name, query}, fn) => {		
		let route = routerArr.find(i => i.name == name)
		let {path, root} = route
		return new Promise((resolve, reject) => {
			uni.navigateTo({
				url: `/${root}/${path}${queryParams(query)}`,
				events: {},
				success: (res) => {
					fn && fn(res)
					resolve(true)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	replace: ({name, query}) => {
		let route = routerArr.find(i => i.name == name)
		let {path, root} = route
		return new Promise((resolve, reject) => {
			uni.redirectTo({
				url: `/${root}/${path}${queryParams(query)}`,
				success: (res) => {
					resolve(true)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	back: (delta = 1) => {
		return new Promise((resolve, reject) => {
			uni.navigateBack({
				delta,
				success: (res) => {
					resolve(true)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	getRoute: (vm) => {
		let {pagePath} = vm.$route.meta
		let item = routerArr.find(i => `${i.root}/${i.path}` == pagePath)
		return item || {}
	},
}